import React, { Component, Fragment } from 'react'
import { connect } from 'react-redux'

// import { getBooksList } from '../../../requests'
import {
  //   getBooksList,
  bookCancelCollect,
  getMyBooksList,
  bookBorrow
} from '../../../requests/bookDo'
import { antIcon } from '../../loading'
import './index.less'
import { Card, Button, Spin, Pagination, message, Empty } from 'antd'
const mapStateToprops = state => {
  return {
    booksCollectId: state.user.bookscollect
  }
}

@connect(mapStateToprops)
export default class BooksCollect extends Component {
  constructor() {
    super()
    this.state = {
      booksCollectList: [],
      booksborrowList:
        JSON.parse(window.sessionStorage.getItem('usermessage')).borrow === null
          ? ''
          : JSON.parse(
              window.sessionStorage.getItem('usermessage')
            ).borrow.split(','),
      userId: JSON.parse(window.sessionStorage.getItem('usermessage')).userId,
      isLoading: true,
      page: 1,
      total: 0
    }
  }
  //取消收藏按钮
  bookCollectCancel = bookId => {
    const userId = JSON.parse(window.sessionStorage.getItem('usermessage'))
      .userid
    bookCancelCollect({ bookId, userId }).then(resp => {
      console.log(resp)
      if (resp.data.data.status === 1) {
        const usermessage = JSON.parse(
          window.sessionStorage.getItem('usermessage')
        )
        usermessage.collect = resp.data.data.collect
        window.sessionStorage.setItem(
          'usermessage',
          JSON.stringify(usermessage)
        )

        this.setState({
          booksCollectList: this.state.booksCollectList.filter(
            value => value.bookId !== bookId
          )
        })
        message.success('取消成功')
      }
    })
  }
  //书籍借阅按钮
  bookborrow = bookId => {
    console.log(bookId)
    const userId = JSON.parse(window.sessionStorage.getItem('usermessage'))
      .userid
    bookBorrow({ userId, bookId }).then(resp => {
      console.log(resp)
      if (resp.data.data.status === 1) {
        this.setState(
          {
            booksborrowList: resp.data.data.borrow.split(',')
          },
          () => {
            const usermessage = JSON.parse(
              window.sessionStorage.getItem('usermessage')
            )
            usermessage.borrow = resp.data.data.borrow
            window.sessionStorage.setItem(
              'usermessage',
              JSON.stringify(usermessage)
            )
            message.success('借阅成功')
          }
        )
      }
    })
  }
  //页码改变
  onPageChange = currentPage => {
    this.setState({
      page: currentPage
    })
  }
  //到我的借阅页面
  toBorrowPage = () => {
    this.props.history.push('/admin/booksborrow')
  }
  //到书籍展示页
  toBooksShowPage = () => {
    this.props.history.push('/admin/booksshow')
  }
  componentDidMount() {
    const collectListId =
      JSON.parse(window.sessionStorage.getItem('usermessage')).collect || ''
    getMyBooksList({ bookid: collectListId }).then(resp => {
      console.log(resp)
      if (resp.data.data.status === 1) {
        this.setState({
          booksCollectList: resp.data.data.data,
          isLoading: false
        })
      }
    })
  }

  render() {
    return (
      <Card title="书籍收藏" bordered={false} style={{ width: '100%' }}>
        <Spin indicator={antIcon} spinning={this.state.isLoading}>
          {this.state.booksCollectList.length === 0 ? (
            <Empty
              image="https://gw.alipayobjects.com/mdn/miniapp_social/afts/img/A*pevERLJC9v0AAAAAAAAAAABjAQAAAQ/original"
              imageStyle={{
                height: 60
              }}
              description={<span>您没有收藏任何书籍</span>}
            >
              <Button type="primary" onClick={this.toBooksShowPage}>
                去书库
              </Button>
            </Empty>
          ) : (
            <Fragment>
              <div className="booksCollect">
                {this.state.booksCollectList.map((item, index) => {
                  if (
                    (this.state.page - 1) * 12 <= index &&
                    index < this.state.page * 12
                  ) {
                    return (
                      <div key={item.bookId} className="booksCollect-content">
                        <dl>
                          <dt>
                            <img
                              src={require(`../../../assets/booksImages/${
                                item.bookId
                              }.jpg`)}
                              alt=""
                            />
                          </dt>
                          <dd>
                            <span>书名:{item.bookName.substring(0, 13)}</span>
                            <span>作者:{item.author}</span>
                            <span>类型:{item.classify}</span>
                            <span>出版社:{item.bookPress}</span>
                            <span>版本:{item.bookVersion}</span>
                          </dd>
                        </dl>
                        <Button
                          size="small"
                          onClick={this.bookCollectCancel.bind(
                            this,
                            item.bookId
                          )}
                        >
                          取消收藏
                        </Button>
                        {this.state.booksborrowList.includes(item.bookId) ? (
                          <Button size="small" onClick={this.toBorrowPage}>
                            借阅中···
                          </Button>
                        ) : (
                          <Button
                            size="small"
                            onClick={this.bookborrow.bind(this, item.bookId)}
                          >
                            借阅书籍
                          </Button>
                        )}
                      </div>
                    )
                  } else {
                    return null
                  }
                })}
              </div>
              <Pagination
                pageSize={12}
                size="small"
                total={this.state.total}
                className="pagination"
                hideOnSinglePage={true}
                onChange={this.onPageChange}
              />
            </Fragment>
          )}
        </Spin>
      </Card>
    )
  }
}
